package com.hmily.spring.samples.scanner;

import com.hmily.spring.samples.scanner.anno.EnableMapperScanner;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <h1>Mapper注册器。</h1>
 *
 * @author hmilyylimh
 * ^_^
 * @version 0.0.1
 * ^_^
 * @date 2021-10-31
 */
public class MapperRegistrar implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        // 1、获取 EnableMapperScanner 配置的包路径
        List<String> pkgList = parsePkgList(importingClassMetadata);

        // 2、想办法调用扫描器进行扫描
        ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry);
        scanner.registerFilters();
        scanner.doScan(StringUtils.toStringArray(pkgList));
    }

    private List<String> parsePkgList(AnnotationMetadata importingClassMetadata) {
        AnnotationAttributes annoAttrs =
                AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(EnableMapperScanner.class.getName()));

        String[] basePkgs = annoAttrs.getStringArray("value");
        List<String> resultList = new ArrayList<>();
        for (String pkg : basePkgs) {
            if (StringUtils.isEmpty(pkg)) {
                continue;
            }
            resultList.add(pkg);
        }

        return resultList;
    }
}